//package api;
//
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.json.JSONUtil;
//import common.ApplicationVariable;
//import lombok.SneakyThrows;
//import model.Order;
//import model.ResultData;
//import model.UserInfo;
package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.Order;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;
import util.SessionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/orderlist")
public class OrderListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Order> data = new ArrayList<>();
        int state = -1;
        String msg = "未知错误";
        String flag = req.getParameter("flag");
        String sql = "select o.*,u.username from `order` o,userinfo u where o.uid=u.uid";
        if (!StrUtil.isBlank(flag)) { // 查询当前登录用户的订单，否则查询全部订单
            UserInfo userInfo = SessionUtil.getSessionUserInfo(req);
            if (userInfo != null) {
                sql += " and o.uid=" + userInfo.getUid();
            } else {
                // 未登录
                msg = "未登录，非法查询";
            }
        }
        // 查询数据库得到订单列表
        sql += " order by oid desc";
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            Order order = new Order();
            order.setOid(resultSet.getInt("oid"));
            order.setCreatetime(resultSet.getString("createtime"));
            order.setMoney(resultSet.getBigDecimal("money"));
            order.setState(resultSet.getInt("state"));
            order.setUsername(resultSet.getString("username"));
            data.add(order);
        }
        DBUtil.close(resultSet, statement, connection);
        state = 200;
        // 将结果返回给前端
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        new ResultData(state, data, msg)
                )
        );
    }
}

